package cc.z8g.browser.core.config

import android.view.KeyEvent

/**
 * Adapts [KeyEvents][KeyEvent] to [KeyCombos][KeyCombos].
 */
object KeyCombos {
    const val CTRL_F = 1
    const val CTRL_T = 2
    const val CTRL_W = 3
    const val CTRL_Q = 4
    const val CTRL_R = 5
    const val CTRL_TAB = 6
    const val CTRL_SHIFT_TAB = 7
    const val SEARCH = 8
    const val ALT_0 = 9
    const val ALT_1 = 10
    const val ALT_2 = 11
    const val ALT_3 = 12
    const val ALT_4 = 13
    const val ALT_5 = 14
    const val ALT_6 = 15
    const val ALT_7 = 16
    const val ALT_8 = 17
    const val ALT_9 = 18

    /**
     * Adapt the [event] or return null if the key combo is unsupported.
     */
    fun adaptKeyEvent(event: KeyEvent): Int? {
        when {
            event.isCtrlPressed -> when (event.keyCode) {
                KeyEvent.KEYCODE_F -> return CTRL_F // Search in page
                KeyEvent.KEYCODE_T -> return CTRL_T // New tab
                KeyEvent.KEYCODE_W -> return CTRL_W // Close current tab
                KeyEvent.KEYCODE_Q -> return CTRL_Q // Close browser
                KeyEvent.KEYCODE_R -> return CTRL_R // Refresh
                KeyEvent.KEYCODE_TAB -> return if (event.isShiftPressed) {
                    CTRL_SHIFT_TAB // Go back one tab
                } else {
                    CTRL_TAB // Go forward one tab
                }
            }

            event.keyCode == KeyEvent.KEYCODE_SEARCH -> return SEARCH // Highlight search field
            event.isAltPressed -> { // Alt + tab number
                if (event.keyCode in KeyEvent.KEYCODE_0..KeyEvent.KEYCODE_9) {
                    return when (event.keyCode) { // Choose tab by number
                        KeyEvent.KEYCODE_0 -> ALT_0
                        KeyEvent.KEYCODE_1 -> ALT_1
                        KeyEvent.KEYCODE_2 -> ALT_2
                        KeyEvent.KEYCODE_3 -> ALT_3
                        KeyEvent.KEYCODE_4 -> ALT_4
                        KeyEvent.KEYCODE_5 -> ALT_5
                        KeyEvent.KEYCODE_6 -> ALT_6
                        KeyEvent.KEYCODE_7 -> ALT_8
                        KeyEvent.KEYCODE_8 -> ALT_8
                        KeyEvent.KEYCODE_9 -> ALT_9
                        else -> null
                    }
                }
            }
        }
        return null
    }

}
